/*
 * Copyright 2011-2012 Benoit Averty, Samuel Babin, Matthieu Bergere, Thomas Letan, Sacha Percot-Tétu, Florian Teyssier
 * 
 * This file is part of DETIQ-T.
 * 
 * DETIQ-T is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * DETIQ-T is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 * 
 * You should have received a copy of the GNU Lesser General Public License
 * along with DETIQ-T.  If not, see <http://www.gnu.org/licenses/>.
*/

#include "AlgorithmService.h"
#include "../GenericInterface.h"
#include "../Services/WindowService.h"
#include "../Widgets/ImageWidgets/StandardImageWindow.h"

#include <Converter.h>

using namespace genericinterface;
using namespace imagein;

AlgorithmService::AlgorithmService()
{

}

void AlgorithmService::display(GenericInterface* gi)
{
  _toolBar = gi->toolBar(tr("Algorithm"));
}

void AlgorithmService::connect(GenericInterface* gi)
{
  _gi = gi;
  _ws = _gi->windowService();

  QObject::connect(this, SIGNAL(newImageWindowCreated(NodeId, ImageWindow*)),
                    _ws, SLOT(addImage(NodeId,ImageWindow*)));
}

void AlgorithmService::applyAlgorithm(GenericAlgorithm_t<Image::depth_t>* algo)
{
    StandardImageWindow* siw = dynamic_cast<StandardImageWindow*>(_ws->getCurrentImageWindow());
    if (siw != NULL)
    {
        //As long algo can't take image of int as parameter, we have to use displayable images

        const Image* whole_image = siw->makeDispImage(siw->CONS);
        const Image* im = whole_image->crop(siw->selection());

        Image* im_res = (*algo)(im);

        Image_t<int>* im_res2 = Converter<Image>::convertToInt(*im_res);

        StandardImageWindow* siw_res = new StandardImageWindow(siw->getPath(), im_res2);
        emit newImageWindowCreated(_ws->getNodeId(siw), siw_res);
    }
}
